package com.xwm93up.multidatasource;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

/**
 * @Description: desc
 * @Author: xwm93up
 * @Since: 2021/11/12 10:21
 */
@SpringBootApplication
public class MultiDatasourceApplication implements CommandLineRunner {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    // @Qualifier("xwm93upEncryptorBean")
    private StringEncryptor encryptorBean;

    public static void main(String[] args) {
        SpringApplication.run(MultiDatasourceApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Environment environment = applicationContext.getBean(Environment.class);

        // 首先获取配置文件里的原始明文信息
        String mysqlMasterPwd = environment.getProperty("spring.datasource.master.password");
        String mysqlSlave1Pwd = environment.getProperty("spring.datasource.slave1.password");
        String mysqlSlave2Pwd = environment.getProperty("spring.datasource.slave2.password");

        // 加密
        String mysqlMasterEncPwd = encrypt(mysqlMasterPwd);
        String mysqlSlave1EncPwd = encrypt(mysqlSlave1Pwd);
        String mysqlSlave2EncPwd = encrypt(mysqlSlave2Pwd);

        // 打印加密前后的结果对比
        System.out.println( "MySQL的Master节点明文密码为：" + mysqlMasterPwd );
        System.out.println( "MySQL的Slave1节点明文密码为：" + mysqlSlave1Pwd );
        System.out.println( "MySQL的Slave2节点明文密码为：" + mysqlSlave2Pwd );
        System.out.println( "====================================" );
        System.out.println( "MySQL的Master节点明文密码加密后的结果为：" + mysqlMasterEncPwd );
        System.out.println( "MySQL的Slave1节点明文密码加密后的结果为：" + mysqlSlave1EncPwd );
        System.out.println( "MySQL的Slave2节点明文密码加密后的结果为：" + mysqlSlave2EncPwd );

        String encStr = "cRWmdqq8s5tJag7XErOfulucAtsgO4Z4PrnkWo1vhieUtfUnMgPmLcaIeRM8zhg2";
        String str = decrypt(encStr);
        System.out.println("测试解密, 原始密码为：" + str);
    }

    private String encrypt(String originPassord) {
        String encryptStr = encryptorBean.encrypt(originPassord);
        return encryptStr;
    }

    private String decrypt(String encryptedPassword) {
        String decryptStr = encryptorBean.decrypt(encryptedPassword);
        return decryptStr;
    }
}
